<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async函数的含义</title>
</head>
<body>
    <h1>async函数的含义</h1>
    <h2>async函数是Generator函数的语法糖</h2>

    <script>
        // Generator函数写法
        function* gen() {
            const data = yield fetchData();
            console.log(data);
        }

        // async函数写法
        async function fetchAsync() {
            const data = await fetchData();
            console.log(data);
        }

        // 模拟异步请求
        function fetchData() {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve('数据');
                }, 1000);
            });
        }

        // async函数对Generator函数的改进
        // 1. 内置执行器
        fetchAsync(); // 自动执行

        // 2. 更好的语义
        async function getTitle(url) {
            const response = await fetch(url);
            const html = await response.text();
            return html.match(/<title>([\s\S]+)<\/title>/i)[1];
        }

        // 3. 更广的适用性
        async function timeoutPromise() {
            await new Promise(resolve => setTimeout(resolve, 2000));
            return '延迟2秒';
        }

        // 4. 返回值是Promise
        async function f() {
            return 'hello world';
        }
        f().then(v => console.log(v));
    </script>
</body>
</html> 